new Vue({
    el:'.container',
    data:{
        users:[],
        user:{
            id:'',
            name:'',
            age:null,
            sex:'男',
            email:'',
            state:false
        },
        nowIndex:null, // 表示当前操作的用户索引
        all:false, // 是否选中复选框
    },
    methods: {
        generateId(){
            // 时间戳+四位随机数
            let num = '';
            for(let i=0;i<4;i++){
                num += Math.floor(Math.random()*10);
            }
            
            return new Date().getTime()+num;
        },
        addUser(){
            this.user.id = this.generateId();
            this.users.push(this.user);

            this.resetUser();
        },
        resetUser(){
            this.user = {
                id:'',
                name:'',
                age:null,
                sex:'男',
                email:''
            }
        },
        deleteUser(){
            if(this.nowIndex==-1){ // 删除所有
                this.users = [];
            }else if(this.nowIndex==-2){
                // 对数组users进行过滤的操作
                this.users = this.users.filter(user => {
                    return !user.state;  // 返回true表示该用户要保留
                });
            }else{
                this.users.splice(this.nowIndex,1); // 从指定索引位置开始删除元素，删除1个
            }
        },
        checkAll(){
            for(let user of this.users){
                user.state = this.all;
            }
        },
        checkItem(){
            this.all = true;
            for(let user of this.users){
                if(!user.state){
                    this.all = false;
                    break;
                }
            }
        },
        modifyUser(){
            for(let index in this.users){
                if(this.users[index].id ==  this.user.id){
                    this.users.splice(index,1,this.user);
                    this.resetUser();
                    break;
                }
            }
        }
    },
    mounted() {
        let data = localStorage.getItem('users');
        if(data){
            this.users = JSON.parse(data);
        }
    },
    watch:{ // 监听users的变量，只要发生变化，就存储到localStorage中
        users:{
            handler:newValue => {
                localStorage.setItem('users',JSON.stringify(newValue));
            },
            deep:true
        }
    }
})